package com.enation.app.javashop.buyer.api.account;

import com.dag.eagleshop.core.account.model.dto.bankcard.BankCardDTO;
import com.dag.eagleshop.core.account.model.dto.bankcard.QueryBankCardDTO;
import com.dag.eagleshop.core.account.model.dto.base.PageDTO;
import com.dag.eagleshop.core.account.model.dto.base.SortField;
import com.dag.eagleshop.core.account.model.dto.base.ViewPage;
import com.dag.eagleshop.core.account.model.dto.member.MemberDTO;
import com.dag.eagleshop.core.account.model.dto.withdraw.*;
import com.dag.eagleshop.core.account.model.enums.WithdrawAccountTypeEnum;
import com.dag.eagleshop.core.account.model.vo.ApplyWithdrawReqVO;
import com.dag.eagleshop.core.account.service.AccountManager;
import com.dag.eagleshop.core.account.service.BankCardManager;
import com.enation.app.javashop.core.base.model.vo.SmsSendVO;
import com.enation.app.javashop.core.base.rabbitmq.AmqpExchange;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.member.model.dos.LeaderDO;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.LeaderManager;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.util.EnvironmentUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提现控制器
 *
 * @author 孙建
 */
@Api(description = "提现接口模块")
@RestController
@RequestMapping("/account/withdraw")
public class WithdrawController {

    @Autowired
    private MemberManager memberManager;
    @Autowired
    private AccountManager accountManager;
    @Autowired
    private BankCardManager bankCardManager;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private DistributionManager distributionManager;
    @Autowired
    private LeaderManager leaderManager;


    @PostMapping("/queryWithdrawAcount")
    @ApiOperation(value = "查询提现账号信息")
    public Map<String, Object> queryWithdrawAcount() {
        Integer uid = UserContext.getBuyer().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        // 查询支付宝
        QueryWithdrawAccountDTO queryWithdrawAccountDTO = new QueryWithdrawAccountDTO();
        queryWithdrawAccountDTO.setMemberId(accountMemberId);
        queryWithdrawAccountDTO.setType(WithdrawAccountTypeEnum.ALIPAY.getIndex());
        ViewPage<WithdrawAccountDTO> withdrawAccountViewPage = accountManager.queryWithdrawAccountList(new PageDTO<>(1, 1, queryWithdrawAccountDTO));
        List<WithdrawAccountDTO> withdrawAccountList = withdrawAccountViewPage.getRecords();

        // 查询微信
        QueryWithdrawAccountDTO wechatAccountDTO = new QueryWithdrawAccountDTO();
        wechatAccountDTO.setMemberId(accountMemberId);
        wechatAccountDTO.setType(WithdrawAccountTypeEnum.WECHAT.getIndex());
        ViewPage<WithdrawAccountDTO> wechatAccountViewPage = accountManager.queryWithdrawAccountList(new PageDTO<>(1, 1, wechatAccountDTO));
        List<WithdrawAccountDTO> wechatAccountList = wechatAccountViewPage.getRecords();

        // 查询银行卡
        QueryBankCardDTO queryBankCardDTO = new QueryBankCardDTO();
        queryBankCardDTO.setMemberId(accountMemberId);
        PageDTO<QueryBankCardDTO> pageDTO = new PageDTO<>(1, 1, queryBankCardDTO);
        ViewPage<BankCardDTO> bankCardViewPage = bankCardManager.queryList(pageDTO);
        List<BankCardDTO> bankCardList = bankCardViewPage.getRecords();

        // 封装返回值
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("wechatAccount", CollectionUtils.isEmpty(wechatAccountList) ? null : wechatAccountList.get(0));
        resultMap.put("alipayWithdrawAccount", CollectionUtils.isEmpty(withdrawAccountList) ? null : withdrawAccountList.get(0));
        resultMap.put("bankCard", CollectionUtils.isEmpty(bankCardList) ? null : bankCardList.get(0));
        return resultMap;
    }

    @ApiOperation(value = "申请提现", notes = "申请提现")
    @PostMapping(value = "applyWithdraw")
    public ApplyWithdrawRespDTO applyWithdraw(@Valid @RequestBody ApplyWithdrawReqVO applyWithdrawReqVO) {
        Integer uid = UserContext.getBuyer().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        // 查询账户会员   用户关系 团长>自提点>会员
        MemberDTO memberDTO = accountManager.queryMemberById(accountMemberId);
        String memberName = memberDTO.getMemberName();
        String customerType = "【用户】"+memberName;
        // 查询自提点
        LeaderDO leaderDO = leaderManager.getByMemberId(uid);
        if(leaderDO != null){
            // 自提点使用状态 0 禁用 1 启用
            Integer leaderStatus = leaderDO.getStatus();
            // 自提点状态 3 审核通过
            Integer leaderAuditStatus = leaderDO.getAuditStatus();
            if(leaderAuditStatus == 2 && leaderStatus == 1){
                customerType =  "【自提站点】"+memberName;
            }
        }

        // 查询当前人是不是团长
        DistributionDO distributionDO = distributionManager.getDistributorByMemberId(uid);
        if(distributionDO != null){
            // 团长状态 2 审核通过
            Integer disAuditStatus = distributionDO.getAuditStatus();
            // 团长使用状态 0 禁用 1 启用
            Integer disStatus = distributionDO.getStatus();
            if(disAuditStatus == 2 && disStatus == 1){
                customerType =  "【团长】" + memberName;
            }
        }

        // 申请提现
        ApplyWithdrawReqDTO applyWithdrawReqDTO = new ApplyWithdrawReqDTO();
        BeanUtils.copyProperties(applyWithdrawReqVO, applyWithdrawReqDTO);
        applyWithdrawReqDTO.setMemberId(memberDTO.getId());
        applyWithdrawReqDTO.setMemberName(customerType);
        applyWithdrawReqDTO.setWithdrawType(applyWithdrawReqVO.getWithdrawType());
        String applyRemark = applyWithdrawReqVO.getApplyRemark();
        applyWithdrawReqDTO.setApplyRemark(StringUtils.isEmpty(applyRemark) ? "申请提现" : applyRemark);
        ApplyWithdrawRespDTO applyWithdrawRespDTO = accountManager.applyWithdraw(applyWithdrawReqDTO);
        // 数据保存成功 并且是生产环境发短息
        if (applyWithdrawRespDTO.isSuccess() && EnvironmentUtils.isProd()) {
            SmsSendVO smsSendVO = new SmsSendVO();
            smsSendVO.setContent("收到一个新的提现申请，流水号:" + applyWithdrawRespDTO.getWithdrawNo() + "，请及时处理。");
            smsSendVO.setMobile("15960179760");// 罗秋菊手机号
            //发送短信验证码
            amqpTemplate.convertAndSend(AmqpExchange.SEND_MESSAGE, AmqpExchange.SEND_MESSAGE + "_QUEUE",
                    smsSendVO);
        }
        return applyWithdrawRespDTO;
    }


    @PostMapping("/queryWithdrawList")
    @ApiOperation(value = "查询提现记录")
    public ViewPage<WithdrawBillDTO> queryWithdrawList(@ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize) {
        Integer uid = UserContext.getBuyer().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        QueryWithdrawBillDTO queryWithdrawBillDTO = new QueryWithdrawBillDTO();
        queryWithdrawBillDTO.setMemberId(accountMemberId);

        PageDTO<QueryWithdrawBillDTO> pageDTO = new PageDTO<>();
        pageDTO.setPageNum(pageNo);
        pageDTO.setPageSize(pageSize);
        pageDTO.setBody(queryWithdrawBillDTO);
        pageDTO.setOrderBys(new SortField[]{new SortField(false, "create_time")});
        return accountManager.queryWithdrawList(pageDTO);
    }

    /**
     * 获取账户会员id
     */
    private String getAccountMemberId(Integer uid) {
        Member member = memberManager.getModel(uid);
        return member.getAccountMemberId();
    }

}
